﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using CNFM_CROCODILE_LOGO.Core.Domain.ViewModels;
using CNFM_CROCODILE_LOGO.RestClient.Utils;
using CNFM_CROCODILE_LOGO.Services.Interfaces;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace CNFM_CROCODILE_LOGO_Web.Areas.Mobile.Controllers
{
    [Area("Mobile")]
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private readonly IHostingEnvironment _het;
        private IBasicServices _pro;
        //string[] pictureFormatArray = { "png", "jpg", "jpeg", "bmp", "gif", "ico", "PNG", "JPG", "JPEG", "BMP", "GIF", "ICO",
        //    "rm", "rmvb", "mpeg1-4","mov","mtv", "dat","wmv", "avi","3gp","amv","dmv","flv","mp4"};

        string[] pictureFormatArrayImage = { "png", "jpg", "jpeg", "bmp", "gif", "ico", "PNG", "JPG", "JPEG", "BMP", "GIF" };
        string[] pictureFormatArrayVideo = { "ICO", "rm", "rmvb", "mpeg1-4", "mov", "mtv", "dat", "wmv", "avi", "3gp", "amv", "dmv", "flv", "mp4" };

        public UploadController(IHostingEnvironment het, IBasicServices pro)
        {
            this._het = het;
            this._pro = pro;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadFile")]
        public async Task<IActionResult> UploadFile(string id, string typeName)
        {
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);
            string url = string.Empty;
            string filePath = string.Empty;

            var model = new MediaImageModels()
            {
                BllId = id,
                BllType = typeName
            };

            //size > 100MB refuse upload !
            if (size > 104857600)
            {
                return Ok(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("pictures total size > 100MB , server refused !"));
            }

            List<string> filePathResultList = new List<string>();

            foreach (var file in files)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                if (typeName == "企业宣传")
                    filePath = _het.WebRootPath + $@"\Files\Company\Propaganda\";
                else
                    filePath = _het.WebRootPath + $@"\Files\Company\File\";

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                string suffix = fileName.Split('.')[1];

                if (!pictureFormatArrayImage.Contains(suffix) && !pictureFormatArrayVideo.Contains(suffix))
                {
                    return Ok(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("不支持的文件类型!"));
                }

                if (!pictureFormatArrayImage.Contains(suffix))
                    model.Type = "视频";
                else
                    model.Type = "图片";

                fileName = Guid.NewGuid() + "." + suffix;

                string fileFullName = filePath + fileName;

                using (FileStream fs = System.IO.File.Create(fileFullName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                if (typeName == "企业宣传")
                    filePathResultList.Add($"/Files/Company/Propaganda/{fileName}");
                else
                    filePathResultList.Add($"/Files/Company/File/{fileName}");
                url = string.Format("{0}{1}", "https://localhost:5001", filePathResultList.FirstOrDefault());

                model.FileUrl = filePathResultList.FirstOrDefault();

                if (typeName == "企业宣传")
                    _pro.AddEnterPrisePropaganda(model);
                else
                    _pro.AddUpdateEnterPriseImage(model);

            }
            string message = "OK";
            return Ok(Return_Helper_DG.Success_Msg_Data_DCount_HttpCode(message, url, filePathResultList.Count));

        }
    }
}